<template>
  <div>
    <Col :lg="24" :md="16">
    <Card class="warp-card" dis-hover>
      <Row justify="space-between" type="flex">
        <Col>
          <Input
            placeholder="任务名称"
            style="width: 200px;"
            v-model="searchForm.taskName"
          />
          <DatePicker type="daterange" split-panels placeholder="任务时间" :editable="false" :capture="false" @on-change="searchForm.taskPlanTime=$event" style="width: 200px;margin-left:20px;" v-model="searchForm.taskPlanTime"></DatePicker>
          <Select v-model="searchForm.status"  placeholder="任务状态" class="form-width" style="width:200px;margin-left:20px;">
                <Option
                    :key="item.value"
                    :value="item.value"
                    v-for="item in taskStatusList"
                  >{{ item.label }}</Option>
            </Select>
            <Select v-model="searchForm.priorityId"  placeholder="优先级" class="form-width" style="width:200px;margin-left:20px;">
                <Option
                    :key="item.id"
                    :value="item.id"
                    v-for="item in priorityList"
                  >{{ item.label }}</Option>
            </Select>
          <Button
            @click="searchData" icon="md-search"
            style="margin-left: 20px;"
            type="primary"
            v-privilege="'search-task'"
          >查询
          </Button>
          <Button
            @click="clearSearch"
            style="margin-left: 20px;"
            icon="md-refresh"
            type="default"
            v-privilege="'search-task'"
          >重置
          </Button>
        </Col>
        <Col>
          <Button
            @click="isShowAddModal=true"
            icon="md-add"
            type="primary"
            v-privilege="'add-task'"
          >新建
          </Button>
        </Col>
      </Row>
      <!-- Form 搜索按钮区 end -->
      <Row style="padding-top:10px; ">
        <Table :columns="columns" :data="data" :loading="isShowTablesLoading" ref="tablesMain"></Table>
      </Row>
      <Row class="page" justify="end" style="position: relative;margin-top: 10px;" type="flex">
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :total="totalPage"
          @on-change="changePage"
          show-total
          show-elevator
        ></Page>
      </Row>
    </Card>
    <!-- Card 内容区 end -->
    <Modal
      :loading="isShowUpdateLoading"
      :closable="false"
      :title="searchType=='edit'?'编辑任务':'查看任务'"
      width="740"
      v-model="isShowEditModal"
    >
      <Form :label-width="80" :model="updateItem" :rules="updateValidate" ref="updateRef">
        <FormItem label="任务编号" prop="taskCode">
          <Input placeholder="任务编号" v-model="updateItem.taskCode" :disabled="updateItem.id!=null"></Input>
        </FormItem>
         <FormItem label="任务名称" prop="taskName">
          <Input placeholder="请输入任务名称(必填)" v-model="updateItem.taskName" :disabled="searchType=='detail'?true:false"></Input>
        </FormItem>
        <FormItem label="计划总数" prop="planNum">
          <Tooltip content="计划总数要大于原来的值" :disabled="true" :always="showPlanNumTooltip" :delay="5000">
            <Input placeholder="请输入计划总数(必填)" v-model="updateItem.planNum" style="width: 300px" :disabled="searchType=='detail'?true:false" type="number"></Input>
          </Tooltip>
        </FormItem>
         <FormItem label="任务时间">
           <Row>
             <Col span="8">
               <FormItem prop="planStartTime">
                 <DatePicker type="datetime" @on-change="updateItem.planStartTime=$event" format="yyyy-MM-dd HH:mm:ss" placeholder="计划开始时间" style="width: 200px" 
                 :disabled="searchType=='detail'?true:false" :editable="false"
                 v-model="updateItem.planStartTime"></DatePicker>
               </FormItem>
             </Col>
             <Col span="1" style="text-align: center">-</Col>
             <Col span="8">
               <FormItem prop="planEndTime">
                 <DatePicker type="datetime" @on-change="updateItem.planEndTime=$event" format="yyyy-MM-dd HH:mm:ss" placeholder="计划结束时间" style="width: 200px" 
                 :disabled="searchType=='detail'?true:false" :editable="false"
                 v-model="updateItem.planEndTime"></DatePicker>
               </FormItem>
               <!--                  <DatePicker type="datetime" @on-change="updateItem.planEndTime=$event" format="yyyy-MM-dd HH:mm:ss" placeholder="计划结束时间" style="width: 200px" v-model="updateItem.planEndTime"></DatePicker>-->
             </Col>
            </Row>
        </FormItem>
        <FormItem class="select-class" label="优先级" prop="priorityId">
            <Select class="form-width" v-model="updateItem.priorityId" @on-select='selectPriority' style="width: 300px" :disabled="searchType=='detail'?true:false">
              <Option
                :key="item.id"
                :value="item.id"
                v-for="item in priorityList"
              >{{ item.label }}</Option>
            </Select>
        </FormItem>
        <FormItem label="任务描述" prop="taskDesc">
          <Input
            :autosize="{minRows: 5, maxRows: 8 }"
            :maxlength="maxlength"
            @input="descInput"
            placeholder="请输入任务描述"
            :disabled="searchType=='detail'?true:false"
            type="textarea"
            v-model="updateItem.taskDesc "
          ></Input>
          <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="cancelUpdateData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndUpdateTask"
          v-if="searchType==='edit'"
        >确定</Button>
      </div>
    </Modal>
    <Modal
      :loading="isShowSaveLoading"
      title="新建任务"
      :closable="false"
      width="740"
      v-model="isShowAddModal"
    >
      <Form :label-width="80" :model="saveItem" :rules="saveValidate" ref="saveRef">
        <FormItem label="任务编号" prop="taskCode">
          <Input placeholder="系统自动分配" v-model="saveItem.taskCode" disabled style="width: 300px"></Input>
        </FormItem>
         <FormItem label="任务名称" prop="taskName">
          <Input :maxlength="30" placeholder="请输入任务名称(必填)" v-model="saveItem.taskName" style="width: 300px"></Input>
        </FormItem>
        <FormItem label="计划总数" prop="planNum">
          <Input-number :max="9999" :min="1" v-model="saveItem.planNum"  placeholder="请输入计划总数(必填)" style="width: 300px"></Input-number>
        </FormItem>
        <FormItem label="任务时间">
           <Row>
                <Col span="8">
                  <FormItem prop="planStartTime">
                    <DatePicker type="datetime" @on-change="saveItem.planStartTime=$event" :editable="false" format="yyyy-MM-dd HH:mm:ss" placeholder="计划开始时间" style="width: 200px" v-model="saveItem.planStartTime"></DatePicker>
                  </FormItem>
<!--                    <DatePicker type="datetime" @on-change="saveItem.planStartTime=$event" format="yyyy-MM-dd HH:mm:ss" placeholder="计划开始时间" style="width: 200px" v-model="saveItem.planStartTime"></DatePicker>-->
                </Col>
                <Col span="1" style="text-align: center">-</Col>
                <Col span="8">
                  <FormItem prop="planEndTime">
                    <DatePicker type="datetime" @on-change="saveItem.planEndTime=$event" :editable="false" format="yyyy-MM-dd HH:mm:ss" placeholder="计划结束时间" style="width: 200px" v-model="saveItem.planEndTime"></DatePicker>
                  </FormItem>
<!--                  <DatePicker type="datetime" @on-change="saveItem.planEndTime=$event" format="yyyy-MM-dd HH:mm:ss" placeholder="计划结束时间" style="width: 200px" v-model="saveItem.planEndTime"></DatePicker>-->
                </Col>
            </Row>
        </FormItem>
        <FormItem class="select-class" label="优先级" prop="priorityId">
            <Select class="form-width" v-model="saveItem.priorityId" @on-select='selectPriority' placeholder="请选择" style="width: 300px">
              <Option
                :key="item.id"
                :value="item.id"
                v-for="item in priorityList"
              >{{ item.label }}</Option>
            </Select>
        </FormItem>
        <FormItem label="任务描述" prop="taskDesc">
          <Input
            :autosize="{minRows: 5, maxRows: 8 }"
            :maxlength="maxlength"
            @input="descInput"
            placeholder="请输入任务描述"
            type="textarea"
            v-model="saveItem.taskDesc "
          ></Input>
          <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="cancelSaveData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndAddTask"
        >确定</Button>
      </div>
    </Modal>
    <!-- Modal 添加任务弹窗 end -->
    </Col>
  </div>
</template>

<script>
import { detectTaskApi } from '@/api/detect-task-manage';
import { validateTextLength} from '@/lib/util';

export default {
  name: 'taskManage',
  components: {},
  props: {},
  data() {
    const planNumValidator = (rule, value, callback) => {
      let errors = []
      if (!value) {
        callback(new Error('请输入计划总数'))
      } else if (!/^[1-9]\d*$/.test(value)) {
        callback(new Error('计划总数格式错误'))
      } else if (this.updateItem.status!='0'&&value < this.updateItem.oldPlanNum) {
        callback(new Error('计划总数不能小于原来的值'))
      } else {
        callback(errors)
      }
    }
    return {
      isShowPage: true,
      searchValue: '',
      remnant: 200,
      maxlength:200,
      searchType:"edit",
      disablePlanNumTooltip: true,
      showPlanNumTooltip: false,
      taskStartStatusList: ['0','2','4'],
      taskStatusList:[
        { value:"0",
          label:'未开始'
        },
        { value:"1",
          label:'运行中'
        },
        { value:"2",
          label:'暂停'
        }
      ],
      priorityList:[
        { id:1,
          label:'普通'
        },
        { id:2,
          label:'重要'
        },
        { id:3,
          label:'紧急'
        }
      ],
      isShowEditModal: false,
      isShowAddModal: false,
      // table是否Loading
      isShowTablesLoading: true,
      isShowSaveLoading: true,
      isShowUpdateLoading: true,
      totalPage: 0,
      // 更新的数据
      updateItem: {
        id:'',
        priorityId:'',
        taskName: '',
        planNum: 0,
        planStartTime:'',
        planEndTime:'',
        taskDesc: '',
        status:''
      },
      // 添加保存的数据
      saveItem: {
        priorityId:'',
        planNum: 1,
        taskName: '',
        planStartTime:'',
        planEndTime:'',
        taskDesc: ''
      },
      saveItemInt: {},
      // table表头
      columns: [
        {
          title: '任务名称',
          width: 100,
          align: "left",
          key: 'taskName'
        },
        {
          title: '计划总数',
          align: "left",
          key: 'planNum',
          width: 80
        },
        {
          title: '计划开始时间',
          width: 160,
          align: "left",
          key: 'planStartTime'
        },
        {
          title: '计划结束时间',
          width: 160,
          align: "left",
          key: 'planEndTime'
        },
         {
          title: '优先级',
          width: 80,
          align: "left",
          key: 'priorityDesc',render: (h, params) => {
           return h('div',[
            h('span', {
              style: {
                  color: (params.row.priorityId===3)?"#ed3f14":(params.row.priorityId===2?"#19be6b":"#2d8cf0")
                }
              }, params.row.priorityDesc)
            ]);
          }
        },
        {
          title: '任务状态',
          width: 80,
          align: "left",
          key: 'statusDesc',render: (h, params) => {
           return h('div',[h('span', {
              style: {
                  color: (params.row.status!=='0'&&params.row.status!=='2'&&params.row.status!=='4')?"#19be6b":"#AAAAAA"
                }
              }, '●'),
            h('span', params.row.statusDesc)
            ]);
          }
        },
        {
          title: "任务进度",
          key: "progress",
          align: "left",
          width: 180,
          render: (h, params) => {
            return h(
              "Progress",
              {
                props: {
                  type: "Progress",
                  size: "small",
                  percent: parseFloat(
                    params.row.progress == null ? 0 : params.row.progress
                  ),
                },
              },
              params.row.progress == null ? "0%" : params.row.progress + "%"
            );
          },
        },
         {
          title: '任务描述',
          width: 200,
          align: "left",
          key: 'taskDesc'
        },
        {
          title: '创建人',
          width: 100,
          align: "left",
          key: 'createByName'
        },
        {
          key: 'createTime',
          width: 160,
          title: '创建时间',
          align: 'left'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            let btnGroup = [];
            if(params.row.status==='0'||params.row.status==='2'||params.row.status==='4'){
              btnGroup.push({
                title: '启动',
                directives: [
                  {
                    name: 'privilege',
                    value: 'start-task'
                  }
                ],
                action: () => {
                  const th = this;
                  this.startOrPauseTask(th,params)
                }
            })}
            if(params.row.status==='1'){
              btnGroup.push({
                title: '暂停',
                directives: [
                  {
                    name: 'privilege',
                    value: 'pause-task'
                  }
                ],
                action: () => {
                  const th = this;
                  this.startOrPauseTask(th,params)
                }
            })}
            if (params.row.status != '3'&&params.row.status != '5') {
              btnGroup.push({
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'update-task'
                  }
                ],
                action: () => {
                  this.getTaskDetail(params.row.id)
                  this.searchType = 'edit';
                  this.isShowEditModal = true
                }
              });
            }
            if (params.row.status == '3'||params.row.status == '5') {
              btnGroup.push({
                title: '查看',
                directives: [
                  {
                    name: 'privilege',
                    value: 'search-task'
                  }
                ],
                action: () => {
                  this.getTaskDetail(params.row.id)
                  this.searchType = 'detail';
                  this.isShowEditModal = true
                }
              });
            }
            if (params.row.status !== '3') {
              btnGroup.push({
                title: '删除',
                directives: [
                  {
                    name: 'privilege',
                    value: 'delete-task'
                  }
                ],
                action: () => {
                  this.deleteTask(params.row)
                }
              });
            }
            return this.$tableAction(h,btnGroup);
          }
        }
      ],
      // table数据
      data: [],
      updateValidate: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        planNum: [{ validator: planNumValidator, trigger: 'blur'}],
        priorityId: [{ required: true, message: '请选择任务优先级', trigger: 'change',type:'number' }],
        planStartTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change',pattern: /.+/}],
        planEndTime: [{ required: true, message: '请选择计划结束时间', trigger: 'change',pattern: /.+/}]
      },
      saveValidate: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        priorityId: [{ required: true, message: '请选择任务优先级', trigger: 'change',type:'number' }],
        planStartTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change',pattern: /.+/}],
        planEndTime: [{ required: true, message: '请选择计划结束时间', trigger: 'change',pattern: /.+/}]
      },
      searchForm: {
        taskName: '',
        taskPlanTime:'',
        planStartTime:'',
        planEndTime:'',
        pageNum: 1,
        pageSize: 10,
        status:'',
        priorityId:'',
        searchCount: true,
        sort: false
      },
      searchFormInt: {},
    };
  },
  computed: {},
  watch: {
    isShowAddModal(val) {
      if (val) {
        this.remnant = 0;
        this.selectPriority();
      }
    },
    isShowEditModal(val) {
      if (val) {
        this.selectPriority();
      }
    },
    'updateItem.planNum': {
      handler(newVal) {
        if (newVal && newVal < this.updateItem.oldPlanNum) {
          this.showPlanNumTooltip = true
        } else {
          this.showPlanNumTooltip = false
        }
      }
    }
  },
  filters: {},
  created() {},
  mounted() {
    Object.assign(this.searchFormInt, this.searchForm);
    Object.assign(this.saveItemInt, this.saveItem);
    this.getTaskByPage();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    async getTaskByPage() {
      try {
        this.isShowTablesLoading = true;
        this.isShowPage = true;
        if(this.searchForm.taskPlanTime&&this.searchForm.taskPlanTime.length>0){
          this.searchForm.planStartTime = this.searchForm.taskPlanTime[0]
          this.searchForm.planEndTime = this.searchForm.taskPlanTime[1]
        }
        let result = await detectTaskApi.getTaskByPage(this.searchForm);
        this.isShowTablesLoading = false;
        let datas = result.data;
        this.data = datas.list;
        this.totalPage = datas.total;
      } catch (e) {
        this.isShowTablesLoading = false;
        console.error(e);
      }
    },
    descInput() {
      let taskDesc = this.updateItem.id?this.updateItem.taskDesc:this.saveItem.taskDesc;
      let txtVal = validateTextLength(taskDesc);
      this.remnant = this.maxlength - txtVal;
    },
     async selectPriority(){
      // let result = await detectTaskApi.getOrgList();
      // this.priorityList = result.data;
    },
     async getTaskDetail(taskId){
      let res = await detectTaskApi.queryTaskById(taskId);
      const data = res.data
      this.updateItem = { ...data }
      this.updateItem.oldPlanNum = data.planNum
      this.descInput()
    },
    async deleteTask(row) {
      if (row.status === '3') {
        this.$Message['error']({
          background: true,
          content: '完成的任务不允许删除'
        });
        return
      }
      let tipMsg;
      if (row.status === '1') {
        tipMsg = '任务<span style="color:red">' + row.taskName + '</span>正在运行，确认删除？'
      } else {
        tipMsg = '确认删除任务<span style="color:red">' + row.taskName + '</span>？'
      }

      this.$Modal.confirm({
        title: '提示',
        content: '<p>' + tipMsg  + '</p>',
        onOk: () => {
          detectTaskApi.deleteTaskById(row.id)
            .then(res => {
              if (res.code === 1) {
                this.$Message.info('任务删除成功');
                this.getTaskByPage();
                this.cancelSaveData();
              }
            })
        },
        onCancel: () => {
        }
      });
    },
  formatDate(date, fmt = 'yyyy-MM-dd') {
    if (typeof (date) === 'number'||typeof(date)==='string') {
      date = new Date(date)
    }
    let o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
    for (let k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
    return fmt
  },
    // 页码改变
    changePage(pageNum) {
      this.searchForm.pageNum = pageNum;
      this.getTaskByPage();
    },
    // 改变每页显示数据条数
    changePageSize(pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.getTaskByPage();
    },
    async startOrPauseTask(h,params) {
      try {
        this.isShowTablesLoading = true;
        let taskId = params.row.id;
        let status = params.row.status;
        if (this.taskStartStatusList.includes(status)) {
          let result = await detectTaskApi.startTask(taskId);
          this.$Message.success('启动成功');
        } else {
          let result = await detectTaskApi.pauseTask(taskId);
          this.$Message.success('暂停成功');
        }
        this.isShowTablesLoading = false;
        await this.getTaskByPage();
      } catch (e) {
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 检验参数后 更新任务
    validateAndUpdateTask() {
      this.$refs['updateRef'].validate(valid => {
        this.isShowUpdateLoading = true;
        if (valid) {
          this.updateTask();
        } else {
          this.isShowUpdateLoading = false;
          this.$nextTick(() => {
            this.isShowUpdateLoading = true;
          });
        }
      });
    },
    // 更新任务
    async updateTask() {
      try {
        let planStartTime = this.updateItem.planStartTime
        let planEndTime = this.updateItem.planEndTime
        this.updateItem.planStartTime = this.formatDate(planStartTime,'yyyy-MM-dd hh:mm:ss')
        this.updateItem.planEndTime = this.formatDate(planEndTime,'yyyy-MM-dd hh:mm:ss')
        let result = await detectTaskApi.updateTask(this.updateItem);
        this.$Message.success('修改成功');
        this.$emit('updateSuccess');
        await this.getTaskByPage();
        this.cancelUpdateData();
      } catch (e) {
        this.isShowUpdateLoading = false;
        this.$nextTick(() => {
          this.isShowUpdateLoading = true;
        });
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowUpdateLoading = false;
      }
    },
    // 清除编辑模态框数据
    cancelUpdateData() {
      this.updateItem = {};
      // 清空form规则检查
      this.$refs['updateRef'].resetFields();
      this.isShowEditModal = false;
    },
    // 搜索
    searchData() {
      this.pageNum = 1;
      this.getTaskByPage();
    },
    // 重置
    clearSearch() {
      Object.assign(this.searchForm, this.searchFormInt);
      this.getTaskByPage();
    },
    // 新增任务
    validateAndAddTask() {
      try {
        this.$refs['saveRef'].validate(valid => {
          this.isShowSaveLoading = true;
          if (valid) {
            this.addTask();
          } else {
            this.isShowSaveLoading = false;
            this.$nextTick(() => {
              this.isShowSaveLoading = true;
            });
          }
        });
      } catch (e) {
        console.error(e);
      }
    },
    // 新增任务 - 异步
    async addTask() {
      try {
        let planStartTime = this.saveItem.planStartTime
        let planEndTime = this.saveItem.planEndTime
        this.saveItem.planStartTime = this.formatDate(planStartTime,'yyyy-MM-dd hh:mm:ss')
        this.saveItem.planEndTime = this.formatDate(planEndTime,'yyyy-MM-dd hh:mm:ss')
        let result = await detectTaskApi.addTask(this.saveItem);
        this.$Message.success('添加成功');
        this.$emit('addSuccess');
        this.isShowSaveLoading = true;
        await this.getTaskByPage();
        this.cancelSaveData();
      } catch (e) {
        console.error(e);
        this.isShowSaveLoading = false;
      }
    },
    // 清除添加模态框数据
    cancelSaveData() {
      Object.assign(this.saveItem, this.saveItemInt);
      // 清空form规则检查
      this.$refs['saveRef'].resetFields();
      this.isShowAddModal = false;
    },
    // 根据ID删除任务
    async deleteTaskById(id) {
      try {
        this.isShowdeleteLoading = true;
        let result = await detectTaskApi.deleteTaskById(id);
        this.isShowdeleteLoading = false;
        this.$Message.success('删除成功');
        await this.getTaskByPage();
        this.cancelSaveData();
      } catch (e) {
        console.error(e);
        this.isShowdeleteLoading = false;
      }
    },
    planNumChange(event) {
      console.log('planNumChange', event);
    }
  }
};
</script>
<style lang="less" scoped>
.form-width {
  width: 100%;
}
.text{
    position: absolute;
    right: 10px;
    bottom: -5px;
}
</style>
